package com.shujia.udf;

import org.apache.hadoop.hive.common.type.Date;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDTF;
import org.apache.hadoop.hive.serde2.objectinspector.*;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

public class UdtfDemo2 extends GenericUDTF {
    @Override
    public StructObjectInspector initialize(StructObjectInspector argOIs) {
        ArrayList<String> namelist = new ArrayList<>();
        ArrayList<ObjectInspector> objectInspectors = new ArrayList<>();
        namelist.add("task");
        objectInspectors.add(PrimitiveObjectInspectorFactory.javaStringObjectInspector);
        StandardStructObjectInspector instance = null;
        Class<StandardStructObjectInspector> inspectorClass = StandardStructObjectInspector.class;
        try {
            Constructor<StandardStructObjectInspector> constructor = inspectorClass.getDeclaredConstructor(List.class, List.class);
            constructor.setAccessible(true);
            instance = constructor.newInstance(namelist, objectInspectors);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException | InstantiationException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }
        return instance;

    }

    @Override
    public void process(Object[] objects) throws HiveException {
        StringBuilder sb = new StringBuilder();
        for (Object o:objects){
            sb.append(o.toString());
        }
        forward(sb);
    }

    @Override
    public void close() throws HiveException {

    }
}
